// 存储服务
const { app } = require('electron');
const fs = require('fs-extra');
const path = require('path');

class StorageService {
    constructor() {
        this.userDataPath = app.getPath('userData');
        this.configPath = path.join(this.userDataPath, 'config.json');
        this.cachePath = path.join(this.userDataPath, 'cache');
        this.workspaceHistoryPath = path.join(this.userDataPath, 'workspace-history.json');
        
        this.ensureDirectories();
    }

    /**
     * 确保目录存在
     */
    ensureDirectories() {
        fs.ensureDirSync(this.userDataPath);
        fs.ensureDirSync(this.cachePath);
    }

    /**
     * 保存 API Key
     * @param {string} apiKey - API KEY
     */
    async saveApiKey(apiKey) {
        try {
            const config = await this.getConfig();
            config.apiKey = apiKey;
            await fs.writeJson(this.configPath, config, { spaces: 2 });
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 读取 API Key
     */
    async loadApiKey() {
        try {
            const config = await this.getConfig();
            return { success: true, apiKey: config.apiKey || null };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 保存完整的模型配置
     * @param {object} modelConfig - 模型配置对象
     * @param {string} modelConfig.provider - 模型厂商 (deepseek, zhipu, gemini)
     * @param {string} modelConfig.model - 模型名称
     * @param {string} modelConfig.apiKey - API Key
     */
    async saveModelConfig(modelConfig) {
        try {
            const config = await this.getConfig();
            
            // 根据厂商自动生成 baseURL
            const baseURLMap = {
                deepseek: 'https://api.deepseek.com/anthropic',
                zhipu: 'https://open.bigmodel.cn/api/anthropic',
                gemini: 'https://generativelanguage.googleapis.com/v1beta'
            };

            // 保存配置
            config.provider = modelConfig.provider;
            config.model = modelConfig.model;
            config.apiKey = modelConfig.apiKey;
            config.baseURL = baseURLMap[modelConfig.provider] || baseURLMap.zhipu;
            config.lastUpdated = new Date().toISOString();

            await fs.writeJson(this.configPath, config, { spaces: 2 });
            return { success: true, config };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 读取模型配置
     * @returns {object} 包含 provider, model, apiKey, baseURL 的配置对象
     */
    async loadModelConfig() {
        try {
            const config = await this.getConfig();
            return {
                success: true,
                config: {
                    provider: config.provider || null,
                    model: config.model || null,
                    apiKey: config.apiKey || null,
                    baseURL: config.baseURL || 'https://open.bigmodel.cn/api/anthropic'
                }
            };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 保存配置
     * @param {object} config - 配置对象
     */
    async saveConfig(config) {
        try {
            await fs.writeJson(this.configPath, config, { spaces: 2 });
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 获取配置
     */
    async getConfig() {
        try {
            if (await fs.pathExists(this.configPath)) {
                return await fs.readJson(this.configPath);
            }
            return {};
        } catch (error) {
            console.error('读取配置失败:', error);
            return {};
        }
    }

    /**
     * 保存任务历史
     * @param {object} taskData - 任务数据
     */
    async saveTaskHistory(taskData) {
        try {
            const historyPath = path.join(this.userDataPath, 'task-history.json');
            let history = [];
            
            if (await fs.pathExists(historyPath)) {
                history = await fs.readJson(historyPath);
            }
            
            history.unshift({
                id: Date.now().toString(),
                timestamp: new Date().toISOString(),
                ...taskData
            });
            
            // 只保留最近100条记录
            history = history.slice(0, 100);
            
            await fs.writeJson(historyPath, history, { spaces: 2 });
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 获取任务历史
     * @param {number} limit - 限制数量
     */
    async getTaskHistory(limit = 50) {
        try {
            const historyPath = path.join(this.userDataPath, 'task-history.json');
            
            if (!await fs.pathExists(historyPath)) {
                return { success: true, history: [] };
            }
            
            const history = await fs.readJson(historyPath);
            return { success: true, history: history.slice(0, limit) };
        } catch (error) {
            return { success: false, message: error.message, history: [] };
        }
    }

    /**
     * 清理缓存
     */
    async clearCache() {
        try {
            await fs.remove(this.cachePath);
            await this.ensureDirectories();
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 获取工作路径的历史记录结构
     */
    async getWorkspaceHistory() {
        try {
            if (await fs.pathExists(this.workspaceHistoryPath)) {
                return await fs.readJson(this.workspaceHistoryPath);
            }
            return {
                workspaces: {},  // 按工作路径组织的历史
                globalHistory: []  // 全局历史（跨所有路径）
            };
        } catch (error) {
            console.error('读取工作路径历史失败:', error);
            return { workspaces: {}, globalHistory: [] };
        }
    }

    /**
     * 保存工作路径任务历史
     * @param {string} workPath - 工作路径
     * @param {object} taskData - 任务数据
     */
    async saveWorkspaceTaskHistory(workPath, taskData) {
        try {
            const history = await this.getWorkspaceHistory();
            
            // 确保工作路径记录存在
            if (!history.workspaces[workPath]) {
                history.workspaces[workPath] = {
                    path: workPath,
                    displayName: path.basename(workPath),
                    firstAccess: new Date().toISOString(),
                    lastAccess: new Date().toISOString(),
                    tasks: []
                };
            }
            
            // 生成任务标题（智能截取或总结）
            const title = this.generateTaskTitle(taskData.task);
            
            // 创建任务记录
            const taskRecord = {
                id: Date.now().toString(),
                title: title,  // 自动生成的标题
                task: taskData.task,
                result: taskData.result || null,
                status: taskData.status || 'success',
                timestamp: new Date().toISOString(),
                duration: taskData.duration || null,
                messageCount: taskData.messageCount || null
            };
            
            // 添加到工作路径的任务列表
            history.workspaces[workPath].tasks.unshift(taskRecord);
            
            // 只保留最近50条
            history.workspaces[workPath].tasks = history.workspaces[workPath].tasks.slice(0, 50);
            
            // 更新最后访问时间
            history.workspaces[workPath].lastAccess = new Date().toISOString();
            
            await fs.writeJson(this.workspaceHistoryPath, history, { spaces: 2 });
            
            console.log('[StorageService] 保存任务历史:', {
                workPath,
                taskId: taskRecord.id,
                workspaceCount: history.workspaces[workPath].tasks.length
            });
            
            return { success: true, taskId: taskRecord.id };
        } catch (error) {
            console.error('[StorageService] 保存任务历史失败:', error);
            return { success: false, message: error.message };
        }
    }

    /**
     * 获取指定工作路径的任务历史
     * @param {string} workPath - 工作路径
     * @param {number} limit - 限制数量
     */
    async getWorkspaceTaskHistory(workPath, limit = 20) {
        try {
            const history = await this.getWorkspaceHistory();
            
            if (!history.workspaces[workPath]) {
                return { success: true, tasks: [] };
            }
            
            const tasks = history.workspaces[workPath].tasks.slice(0, limit);
            return { success: true, tasks };
        } catch (error) {
            console.error('[StorageService] 获取任务历史失败:', error);
            return { success: false, message: error.message, tasks: [] };
        }
    }

    /**
     * 获取所有工作路径列表（按最近使用排序）
     */
    async getWorkspaceList() {
        try {
            const history = await this.getWorkspaceHistory();
            
            const workspaces = Object.values(history.workspaces)
                .map(ws => ({
                    path: ws.path,
                    displayName: ws.displayName,
                    lastAccess: ws.lastAccess,
                    taskCount: ws.tasks.length
                }))
                .sort((a, b) => new Date(b.lastAccess) - new Date(a.lastAccess));
            
            return { success: true, workspaces };
        } catch (error) {
            return { success: false, message: error.message, workspaces: [] };
        }
    }

    /**
     * 获取所有工作路径列表（带统计信息，用于历史记录页面）
     */
    async getWorkspaceListWithStats() {
        try {
            const history = await this.getWorkspaceHistory();
            
            const workspaces = Object.values(history.workspaces)
                .map(ws => ({
                    path: ws.path,
                    displayName: ws.displayName,
                    lastAccess: ws.lastAccess,
                    taskCount: ws.tasks.length,
                    lastTask: ws.tasks && ws.tasks.length > 0 ? {
                        title: ws.tasks[0].title,
                        task: ws.tasks[0].task,
                        status: ws.tasks[0].status,
                        timestamp: ws.tasks[0].timestamp
                    } : null
                }))
                .sort((a, b) => new Date(b.lastAccess) - new Date(a.lastAccess));
            
            return { success: true, workspaces };
        } catch (error) {
            console.error('[StorageService] 获取工作区列表失败:', error);
            return { success: false, message: error.message, workspaces: [] };
        }
    }

    /**
     * 获取全局历史记录（跨所有工作路径）
     * @param {number} limit - 限制数量
     */
    async getGlobalTaskHistory(limit = 50) {
        try {
            const history = await this.getWorkspaceHistory();
            const tasks = history.globalHistory.slice(0, limit);
            return { success: true, tasks };
        } catch (error) {
            return { success: false, message: error.message, tasks: [] };
        }
    }

    /**
     * 清除指定工作路径的历史
     * @param {string} workPath - 工作路径
     */
    async clearWorkspaceHistory(workPath) {
        try {
            const history = await this.getWorkspaceHistory();
            
            if (history.workspaces[workPath]) {
                delete history.workspaces[workPath];
                await fs.writeJson(this.workspaceHistoryPath, history, { spaces: 2 });
            }
            
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 清除所有历史记录
     */
    async clearAllHistory() {
        try {
            await fs.writeJson(this.workspaceHistoryPath, {
                workspaces: {}
            }, { spaces: 2 });
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    /**
     * 生成任务标题
     * @param {string} task - 任务描述
     * @returns {string} 标题
     */
    generateTaskTitle(task) {
        if (!task || typeof task !== 'string') {
            return '未命名任务';
        }

        // 移除首尾空白
        const trimmedTask = task.trim();
        
        // 如果是空字符串
        if (!trimmedTask) {
            return '未命名任务';
        }

        // 1. 尝试提取第一句话（以句号、问号、感叹号等结束）
        const firstSentenceMatch = trimmedTask.match(/^[^。！？\n.!?]+[。！？.!?]?/);
        if (firstSentenceMatch) {
            let sentence = firstSentenceMatch[0].trim();
            
            // 如果第一句话长度合适（15-60字符），使用它
            if (sentence.length >= 15 && sentence.length <= 60) {
                return sentence;
            }
            
            // 如果太短，尝试再取一句
            if (sentence.length < 15) {
                const secondSentenceMatch = trimmedTask.match(/^[^。！？\n.!?]+[。！？.!?]?[^。！？\n.!?]+[。！？.!?]?/);
                if (secondSentenceMatch && secondSentenceMatch[0].length <= 60) {
                    sentence = secondSentenceMatch[0].trim();
                }
            }
            
            // 如果太长，截断
            if (sentence.length > 60) {
                sentence = sentence.substring(0, 60) + '...';
            }
            
            return sentence;
        }

        // 2. 如果没有明显的句子结构，取第一行
        const firstLine = trimmedTask.split('\n')[0].trim();
        if (firstLine.length > 0) {
            if (firstLine.length <= 60) {
                return firstLine;
            }
            return firstLine.substring(0, 60) + '...';
        }

        // 3. 如果第一行为空，智能截取
        const words = trimmedTask.replace(/\s+/g, ' ').trim();
        
        // 尝试识别任务类型的关键词
        const keywords = ['创建', '写', '生成', '开发', '设计', '实现', '优化', '修改', '帮我', '请'];
        let hasKeyword = false;
        
        for (const keyword of keywords) {
            if (words.startsWith(keyword) || words.includes(keyword)) {
                hasKeyword = true;
                break;
            }
        }
        
        // 智能截取长度
        let maxLength = hasKeyword ? 50 : 40;
        
        if (words.length <= maxLength) {
            return words;
        }
        
        // 截取到最后一个完整的词
        const truncated = words.substring(0, maxLength);
        const lastSpace = truncated.lastIndexOf(' ');
        
        if (lastSpace > 20) {
            return truncated.substring(0, lastSpace) + '...';
        }
        
        return truncated + '...';
    }
}

module.exports = new StorageService();
